package com.itheima.linkNode;

import com.itheima.util.ListNode;

/**
 * @author MMXZKA
 * @date 2025-07-31 17:30
 */
public class LeeCode92 {

    //给你单链表的头指针 head 和两个整数 left 和 right`
    // ，其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点，返回 反转后的链表 。

    //Definition for singly-linked list.

    public ListNode reverseBetween(ListNode head, int left, int right) {
        // 创建虚拟头节点简化边界处理
        ListNode dummy = new ListNode(0);
        dummy.next = head;

        // 找到反转区间的前一个节点
        ListNode prev = dummy;
        for (int i = 0; i < left - 1; i++) {
            prev = prev.next;
        }

        // 反转区间的第一个节点
        ListNode curr = prev.next;

        // 执行反转操作
        for (int i = 0; i < right - left; i++) {
            ListNode next = curr.next;
            curr.next = next.next;
            next.next = prev.next;
            prev.next = next;
        }

        return dummy.next;
    }
}

 /*
              ListNode leftNodeBefore = new ListNode();
              ListNode rightNodeBefore = new ListNode();
              ListNode node ;
              ListNode newhead = head;
              int count = 0;

              while (true){
                  count++;
                  if (left == 1){
                      leftNodeBefore.next = head;
                  }else {
                      if(count == left-1){
                          leftNodeBefore = head;
                      }
                  }
                  if (count == right-1){
                      rightNodeBefore = head;
                      break;
                  }
                  head = head.next;
              }

              ListNode leftNode = leftNodeBefore.next;
              ListNode rightNode = rightNodeBefore.next;

              node = leftNode.next;
              leftNode.next = rightNode.next;
              if (rightNodeBefore.next != leftNode){
                  rightNodeBefore.next = leftNode;
              }
              rightNode.next = node;
              leftNodeBefore.next = rightNode;

              return newhead;
          }*/


//看错题目了真烦